package com.inspinia.upms.client.filter;

import com.baomidou.kisso.SSOCache;
import com.baomidou.kisso.SSOConfig;
import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.SSOToken;
import com.baomidou.kisso.common.SSOProperties;
import com.baomidou.kisso.common.util.HttpUtil;
import com.baomidou.kisso.web.handler.KissoDefaultHandler;
import com.baomidou.kisso.web.handler.SSOHandlerInterceptor;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AccessControlFilter extends FormAuthenticationFilter {

    private SSOHandlerInterceptor handlerInterceptor;

    @Override
    public boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object mapperValue) {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        //校验token有效性
        try {
            return checkValidate(servletRequest,servletResponse);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 校验token
     * @param servletRequest
     * @param servletResponse
     */
    private boolean checkValidate(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        SSOToken ssoToken = SSOHelper.getToken(request);
        if (ssoToken == null) {

            if (HttpUtil.isAjax(request)) {
                this.getHandlerInterceptor().preTokenIsNullAjax(request, response);
                return false;
            }
            SSOProperties prop = SSOConfig.getSSOProperties();
            if (this.getHandlerInterceptor().preTokenIsNull(request, response)) {
                response.sendRedirect(HttpUtil.encodeRetURL(SSOConfig.getInstance().getLoginUrl(),SSOConfig.getInstance().getParamReturl(),prop.get("sso.defined.proxyloginurl")));
                return false;
            }
            return false;
        }

        request.setAttribute(SSOConfig.SSO_TOKEN_ATTR, ssoToken);
        //token续期
        SSOCache cache = SSOConfig.getInstance().getCache();
        cache.set(ssoToken.toCacheKey(),ssoToken,SSOConfig.getInstance().getCacheExpires());
        return true;
    }


    public SSOHandlerInterceptor getHandlerInterceptor() {
        return (SSOHandlerInterceptor)(this.handlerInterceptor == null ? KissoDefaultHandler.getInstance() : this.handlerInterceptor);
    }

    public void setHandlerInterceptor(SSOHandlerInterceptor handlerInterceptor) {
        this.handlerInterceptor = handlerInterceptor;
    }
}